package com.fary.ibmmq;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ibm.jms.JMSBytesMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.jms.JMSContext;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

/**
 * ibm mq 消息接受者
 */
@Slf4j
@Component
@Scope(SCOPE_PROTOTYPE)
public class MQMessageListener implements MessageListener {
    private JMSContext context;

    public void setContext(JMSContext context) {
        this.context = context;
    }

    @Override
    public void onMessage(Message message) {
        try {
            String text = "";
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                text = textMessage.getText();
            } else if (message instanceof JMSBytesMessage) {
                JMSBytesMessage jmsBytesMessage = (JMSBytesMessage) message;
                byte[] bytes = new byte[1024];
                jmsBytesMessage.readBytes(bytes);
                text = new String(bytes);
            }
            log.info("\n承保返回报文:\n" + JSONUtil.formatJsonStr(text));
            JSONObject respJsonObject = JSONUtil.parseObj(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
        context.commit();
    }
}
